package com.ezjie.ielts.module_set;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.core.base.BaseBean;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.core.spfs.SharedPrefHelper;
import com.ezjie.ielts.db.AudioFileDB;
import com.ezjie.ielts.db.UserInfoDB;
import com.ezjie.ielts.model.UpdateDetail;
import com.ezjie.ielts.module_main.NavigationActivity;
import com.ezjie.ielts.module_personal.ChangeAimActivity;
import com.ezjie.ielts.module_word.OfflineManageActivity;
import com.ezjie.ielts.service.UpdateCompleteService;
import com.ezjie.ielts.task.LogoutTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.OnDialogBtnClickImpl;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.widget.AppWarnDialog;
import com.ezjie.ielts.widget.TitleTextView;
import com.ezjie.login.LoginActivity;
import com.ezjie.login.model.UserDetail;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

/**
 * 设置界面
 * 
 * @author renyangyang
 *
 */
@ContentView(R.layout.layout_settting)
public class SettingActivity extends BaseFragmentActivity {

	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.tv_topbar_title)
	private TitleTextView tv_topbar_title;

	@ViewInject(R.id.mygoal_layout)
	private RelativeLayout mygoal_layout;
	@ViewInject(R.id.rl_offline_layout)
	private RelativeLayout rl_offline_layout;
	@ViewInject(R.id.feedback_layout)
	private RelativeLayout feedback_layout;
	@ViewInject(R.id.check_version_layout)
	private RelativeLayout check_version_layout;
	// @ViewInject(R.id.about_layout)
	// private RelativeLayout about_layout;
	@ViewInject(R.id.clear_cache_layout)
	private RelativeLayout clear_cache_layout;
	@ViewInject(R.id.logout_button)
	private Button logout_button;

	private UserInfoDB userInfoDB;
	private LogoutTask logoutTask;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);

		userInfoDB = new UserInfoDB(this);
		logoutTask = new LogoutTask(this);
		init();

		mContext = this;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_SETTING);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_SETTING);
	}

	private void init() {
		iv_topbar_back.setOnClickListener(this);
		tv_topbar_title.setText(R.string.set_title);

		mygoal_layout.setOnClickListener(this);
		rl_offline_layout.setOnClickListener(this);
		feedback_layout.setOnClickListener(this);
		check_version_layout.setOnClickListener(this);
		// about_layout.setOnClickListener(this);
		clear_cache_layout.setOnClickListener(this);
		logout_button.setOnClickListener(this);
	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			this.finish();
			break;
		case R.id.mygoal_layout:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "personCenter_changeGlobal");
			startActivity(new Intent(SettingActivity.this, ChangeAimActivity.class));
			break;
		case R.id.rl_offline_layout:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "set_my_offline_manage");
			startActivity(new Intent(SettingActivity.this, OfflineManageActivity.class));
			break;
		case R.id.feedback_layout:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "set_feedBack");
			startActivity(new Intent(SettingActivity.this, FeedbackActivity.class));
			break;
		case R.id.check_version_layout:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "set_upgrade");
			UpdateDetail detail = (UpdateDetail) JSON.parse(SharedPrefHelper.getInstance().getUpdateData("updateData"));
			if (null != detail && detail.has_update.equals("1")) {
				// 需要更新
				showUpdateDialog(detail);
			} else {
				AppUtil.showToast(this, R.string.set_is_new_version);
			}
			break;
		// case R.id.about_layout:
		// // 友盟统计
		// MobclickAgent.onEvent(mContext, "set_contactUs");
		// startActivity(new Intent(SettingActivity.this, AboutActivity.class));
		// break;
		case R.id.clear_cache_layout:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "set_clearCache");
			AppWarnDialog appWarnDialog = new AppWarnDialog(this, R.style.customDialog);
			appWarnDialog.show();
			appWarnDialog.setOneButton(false);
			appWarnDialog.setMessage(R.string.set_is_clear_cache);
			appWarnDialog.setYesButton(R.string.confirm);
			appWarnDialog.setNoButton(R.string.cancel);
			appWarnDialog.setKnowButton(R.string.know);
			appWarnDialog.setListener(new OnDialogBtnClickImpl() {
				@Override
				public void onYesClick() {// 清除缓存
					super.onYesClick();
					clearCache();
				}
			});
			break;
		case R.id.logout_button:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "set_logout");
			AppWarnDialog appWarnDialog2 = new AppWarnDialog(this, R.style.customDialog);
			appWarnDialog2.show();
			appWarnDialog2.setOneButton(false);
			appWarnDialog2.setMessage(R.string.set_is_logout);
			appWarnDialog2.setYesButton(R.string.confirm);
			appWarnDialog2.setNoButton(R.string.cancel);
			appWarnDialog2.setKnowButton(R.string.know);
			appWarnDialog2.setListener(new OnDialogBtnClickImpl() {
				@Override
				public void onYesClick() {// 退出登录
					super.onYesClick();
					// 友盟统计
					MobclickAgent.onEvent(mContext, "set_logout_dialog");

					logout();
				}

				@Override
				public void onNoClick() {
					super.onNoClick();
					// 友盟统计
					MobclickAgent.onEvent(mContext, "set_logout_dialog");
				}
			});
			break;
		default:
			break;
		}

	}

	private void showUpdateDialog(final UpdateDetail detail) {
		View view = LayoutInflater.from(mContext).inflate(R.layout.layout_update_msg_dialog, null);

		final Dialog dialog = new Dialog(this, R.style.customDialog);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setContentView(view);
		dialog.show();

		TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
		tv_content.setText(Html.fromHtml(detail.content));
		LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
		LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
		String is_force = detail.is_force;
		if ("1".equals(is_force)) {
			// 强制更新
			ll_layout2.setVisibility(View.VISIBLE);
			ll_layout1.setVisibility(View.GONE);
			dialog.setCancelable(false);
		} else {
			ll_layout2.setVisibility(View.GONE);
			ll_layout1.setVisibility(View.VISIBLE);
			dialog.setCancelable(true);
		}

		Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
		Button btn_no = (Button) view.findViewById(R.id.btn_no);
		Button btn_know = (Button) view.findViewById(R.id.btn_know);

		btn_no.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
			}
		});
		btn_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				startDownloadApk(detail);
			}
		});
		btn_know.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				startDownloadApk(detail);
			}
		});
	}

	private void startDownloadApk(UpdateDetail detail) {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}
		if (detail == null) {
			return;
		}
		// 判断是否有外部存储卡
		String status = Environment.getExternalStorageState();
		if (!status.equals(Environment.MEDIA_MOUNTED)) {
			// 在 vivo X3L报很多次错，Destination must be on external storage
			AppUtil.showToast(this, R.string.cannot_user_sdcard);
			return;
		}
		AppUtil.showToast(this, R.string.update_downing);
		if (null == NavigationActivity.serviceIntent) {
			NavigationActivity.serviceIntent = new Intent(this, UpdateCompleteService.class);
		}
		NavigationActivity.serviceIntent.putExtra("update", detail);
		startService(NavigationActivity.serviceIntent);
	}

	private void clearCache() {
		SharedPrefHelper.getInstance().clearCache();
		new AudioFileDB(mContext).claerData();
		AppUtil.showToast(this, R.string.set_clear_cache_success);
	}

	private void logout() {
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}
		UserDetail queryLoginUser = userInfoDB.queryLoginUser();
		if (queryLoginUser != null && queryLoginUser.islogin == 1) {
			logoutTask.doLogout(new HttpRequestAbstractCallBack(mContext,false) {
				@Override
				public void onStartCallBack() {
					// TODO Auto-generated method stub
					super.onStartCallBack();
					AppUtil.showProgressDialog(SettingActivity.this);
				}

				@Override
				public void onSuccessCallBack(String result) {
					// TODO Auto-generated method stub
					super.onSuccessCallBack(result);
					AppUtil.dismissProgressDialog();
					LogUtils.d(result);
					try {
						BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
						if (baseBean != null) {
							// 把当前用户登录状态设置为0
							UserDetail queryLoginUser = userInfoDB.queryLoginUser();
							if (queryLoginUser != null && queryLoginUser.islogin == 1) {
								queryLoginUser.islogin = 0;
								userInfoDB.update(queryLoginUser);
								// 销毁当前界面和设置界面
								SettingActivity.this.setResult(RESULT_OK);
								SettingActivity.this.finish();

								startActivity(new Intent(mContext, LoginActivity.class));
							}
						}
					} catch (Exception e) {
						LogUtils.exception(e);
					}

				}

				@Override
				public void onFailureCallBack(HttpException error, String msg) {
					// TODO Auto-generated method stub
					super.onFailureCallBack(error, msg);
					AppUtil.dismissProgressDialog();
					AppUtil.showToast(SettingActivity.this, R.string.load_net_data_failure);
				}
			});
		}

	}

}
